package com.speaktoitcookbook.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.speaktoitcookbook.bean.Collection;
import com.speaktoitcookbook.dao.ICollectionDao;
import com.speaktoitcookbook.dao.factory.DaoFactory;
import com.speaktoitcookbook.util.LogUtil;

@WebServlet("/CollectionService")
public class CollectionService extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LogUtil
            .getLogger(CollectionService.class);

    public CollectionService() {
        super();
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");

        String userID = request.getParameter("userID");
        String cbID = request.getParameter("cbID");

        Collection collection = new Collection();
        collection.setUserID(userID);
        collection.setCookbookID(Long.parseLong(cbID));

        ICollectionDao dao = DaoFactory.getCollectionDao();

        boolean result = false;
        try {
            result = dao.doCreate(collection);
        } catch (SQLException e) {
            log.error(e);
        }

        Gson gson = new Gson();
        String msg = gson.toJson(result);
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();

        log.info("用户:" + userID + "收藏菜谱:" + cbID + ",收藏结果:" + msg);
    }
}